package 红包算法;

/**
 * @Author piper
 * @Date 2019/12/24 10:03 上午
 */
public class 红包算法 {
    private static class RedPackage {
        int remainSize; // remainSize 剩余的红包数量
        float remainMoney; // remainMoney 剩余的钱

        RedPackage(int remainSize, float remainMoney) {
            this.remainSize = remainSize;
            this.remainMoney = remainMoney;
        }
    }

    private static double getRandomMoney(RedPackage redPackage) {
        if (redPackage.remainSize == 1) {
            redPackage.remainSize--;
            return (double) Math.round(redPackage.remainMoney * 100) / 100;
        }
        double min = 0.01; //最低金额
        // 这两行是核心算法 1剩下的钱平分，变成两倍 2这个数字 ✖（0-1之间的数字）的到结果会在最大值左右浮动
        double max = redPackage.remainMoney / redPackage.remainSize * 2;
        double money = Math.random() * max;
        money = money <= min ? 0.01 : money;
        money = Math.floor(money * 100) / 100;  //取两位小数
        redPackage.remainSize--;
        redPackage.remainMoney -= money;
        return money;
    }

    public static void main(String[] args) {
        RedPackage redPackage = new RedPackage(5, 8);
        for (int i = 0; i < 5; i++) {
            System.out.println(getRandomMoney(redPackage));
        }
    }

}
